package com.affectu;

import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.hibernate.Session;

import com.affectu.category.Category;
import com.affectu.common.base.UtilBase;
import com.affectu.common.util.PersistanceUtil;
import com.affectu.common.util.ThreadPoolUtil;
import com.affectu.search.fetch.FetchThread;

/**
 * Sep 21, 2008
 * 
 * @author daniel nathan
 */
public class PreJobs extends UtilBase {

	private static final ScheduledExecutorService scheduler = ThreadPoolUtil
			.getScheduledExecutorService();

	private static PreJobs instance = new PreJobs();

	private boolean flag = false;

	private PreJobs() {
	}

	public static PreJobs getInstance() {
		return instance;
	}

	public void start() {
		if (!flag) {
			this.execute();
		}
	}

	private boolean execute() {// only one for need to execute
		synchronized (this) {
			Session session = PersistanceUtil.getInstance().getSession();
			try {
				if (!this.isInit(session)) {
					this.initCategoryTree(session);
				}
				// session.createSQLQuery(PreSQL.VIEW_TASKS_STATEMENT).executeUpdate();
				scheduler.scheduleAtFixedRate(new FetchThread(), 0, 2,
						TimeUnit.HOURS);
				flag = true;
			} catch (Exception ex) {
				this.logException(ex);
			} finally {
				session.close();
			}
			return flag;
		}
	}

	public void stop() {
		if (flag) {
			scheduler.shutdown();
			flag = false;
		}
	}

	private void initCategoryTree(Session session) {
		String[] categoryDes = new String[] {
				"设计:产品外观,VI/CI/UI设计,标志/Logo,装饰/装潢", "文案:策划,写作,翻译",
				"营销:发帖,产品销售", "程序:网站网页,软件,数据库,破解", "劳务:计件,娱乐,招聘,求助" };

		Category root = this.getRoot(session);

		for (String oneLevelName : categoryDes) {
			Category oneLevel = new Category();
			oneLevel.setName(oneLevelName.split(":")[0]);
			oneLevel.setParent(root);
			session.save(oneLevel);

			for (String twoLevelName : oneLevelName.split(":")[1].split(",")) {
				Category twoLevel = new Category();
				twoLevel.setName(twoLevelName);
				twoLevel.setParent(oneLevel);
				session.save(twoLevel);
			}
		}
	}

	@SuppressWarnings("unchecked")
	private Category getRoot(Session session) {
		List<Category> list = session.createQuery(
				"from Category c where c.level=0").list();
		if (list.size() == 0) {
			Category root = new Category();
			root.setName("root");
			root.setLevel(0);
			session.persist(root);
			return root;
		} else {
			return list.get(0);
		}
	}

	@SuppressWarnings("unchecked")
	private boolean isInit(Session session) {
		List<Category> list = session.createQuery("from Category c").list();
		if (list.size() > 0) {
			return true;
		} else {
			return false;
		}
	}
}
